<template>
  <Dialog title="拉黑会员用户" v-model="dialogVisible" width="600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item v-if="userIds.length === 1" label="用户编号" prop="userId">
        <el-input v-model="userInfo.id" placeholder="用户编号" class="!w-240px" disabled />
      </el-form-item>
      <el-form-item v-if="userIds.length === 1" label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname" placeholder="用户昵称" class="!w-240px" disabled />
      </el-form-item>
      <el-form-item v-else label="选中用户">
        <el-text type="primary">已选择 {{ userIds.length }} 位用户</el-text>
      </el-form-item>

      <el-form-item label="拉黑原因" prop="blacklistReason">
        <el-input
          v-model="formData.blacklistReason"
          placeholder="请输入拉黑原因"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="拉黑详情" prop="blacklistDetail">
        <el-input
          type="textarea"
          v-model="formData.blacklistDetail"
          placeholder="请输入拉黑详情（可选）"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- <el-form-item label="限制设置">
        <el-checkbox-group v-model="restrictions">
          <el-checkbox label="restrictLogin">限制登录</el-checkbox>
          <el-checkbox label="restrictOrder">限制下单</el-checkbox>
          <el-checkbox label="restrictComment">限制评论</el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->

      <el-form-item label="到期时间" prop="expireTime">
        <el-radio-group v-model="expireType" @change="handleExpireTypeChange">
          <el-radio value="forever">永久拉黑</el-radio>
          <el-radio value="preset">快捷设置</el-radio>
          <el-radio value="custom">自定义日期</el-radio>
        </el-radio-group>

        <!-- 快捷选项 -->
        <div v-if="expireType === 'preset'" class="mt-10px">
          <el-select
            v-model="presetDays"
            placeholder="选择拉黑时长"
            class="!w-240px"
            @change="handlePresetChange"
          >
            <el-option label="1天" :value="1" />
            <el-option label="3天" :value="3" />
            <el-option label="7天" :value="7" />
            <el-option label="15天" :value="15" />
            <el-option label="30天" :value="30" />
            <el-option label="90天" :value="90" />
            <el-option label="180天" :value="180" />
            <el-option label="365天（1年）" :value="365" />
          </el-select>
        </div>

        <!-- 自定义日期 -->
        <div v-if="expireType === 'custom'" class="mt-10px">
          <el-date-picker
            v-model="formData.expireTime"
            type="datetime"
            placeholder="选择到期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="!w-240px"
            :disabled-date="disabledDate"
          />
        </div>

        <!-- 显示结果 -->
        <div v-if="formData.expireTime" class="mt-5px">
          <el-text size="small" type="warning"> 到期时间：{{ formData.expireTime }} </el-text>
        </div>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="formData.remark"
          placeholder="请输入备注（可选）"
          :rows="2"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="danger" :disabled="formLoading">确认拉黑</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as UserApi from '@/api/member/user'
import type { MemberUserBatchBlacklistReqVO } from '@/api/member/user'

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const userIds = ref<number[]>([]) // 用户ID列表
const userInfo = ref<any>({ id: '', nickname: '' }) // 单个用户信息

const formData = ref<MemberUserBatchBlacklistReqVO>({
  userIds: [],
  blacklistReason: '',
  blacklistDetail: '',
  expireTime: undefined,
  restrictLogin: false,
  restrictOrder: false,
  restrictComment: false,
  remark: ''
})

const formRules = reactive({
  blacklistReason: [
    { required: true, message: '拉黑原因不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
})

const formRef = ref() // 表单 Ref

// 有效期类型
const expireType = ref('forever')
const presetDays = ref<number>()

// 限制设置
const restrictions = ref<string[]>([])

/** 有效期类型改变 */
const handleExpireTypeChange = (type: string) => {
  if (type === 'forever') {
    formData.value.expireTime = undefined
  }
  presetDays.value = undefined
}

/** 快捷选项改变 */
const handlePresetChange = (days: number) => {
  const now = new Date()
  const expireDate = new Date(now.getTime() + days * 24 * 60 * 60 * 1000)
  formData.value.expireTime = formatDateTime(expireDate)
}

/** 格式化日期时间 */
const formatDateTime = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/** 禁用过去的日期 */
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7 // 昨天之前
}

/** 打开弹窗 */
const open = async (ids: number[]) => {
  dialogVisible.value = true
  resetForm()
  userIds.value = ids

  // 如果只选中一个用户，加载用户信息
  if (ids.length === 1) {
    formLoading.value = true
    try {
      const data = await UserApi.getUser(ids[0])
      userInfo.value = {
        id: data.id,
        nickname: data.nickname
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 组装限制设置
  formData.value.restrictLogin = restrictions.value.includes('restrictLogin')
  formData.value.restrictOrder = restrictions.value.includes('restrictOrder')
  formData.value.restrictComment = restrictions.value.includes('restrictComment')

  // 如果没有选择任何限制，至少要限制登录
  // if (
  //   !formData.value.restrictLogin &&
  //   !formData.value.restrictOrder &&
  //   !formData.value.restrictComment
  // ) {
  //   message.warning('请至少选择一项限制设置')
  //   return
  // }

  // 设置用户ID列表
  formData.value.userIds = userIds.value

  // 提交请求
  formLoading.value = true
  try {
    await UserApi.batchBlacklistUsers(formData.value)
    message.success('拉黑成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userIds: [],
    blacklistReason: '',
    blacklistDetail: '',
    expireTime: undefined,
    restrictLogin: false,
    restrictOrder: false,
    restrictComment: false,
    remark: ''
  }
  expireType.value = 'forever'
  presetDays.value = undefined
  restrictions.value = []
  userInfo.value = { id: '', nickname: '' }
  formRef.value?.resetFields()
}
</script>
